package com.voltmaon.shortlink.converter;

import java.sql.Timestamp;
import java.util.Optional;
import javax.persistence.AttributeConverter;

import org.joda.time.DateTime;
import org.joda.time.base.BaseDateTime;

public class DateTimeConverter implements AttributeConverter<DateTime, Timestamp> {
	public static final DateTimeConverter instance = new DateTimeConverter();

	public DateTimeConverter() {
	}

	@Override
	public Timestamp convertToDatabaseColumn(DateTime attribute) {
		return Optional.ofNullable(attribute)
			.map(BaseDateTime::getMillis)
			.map(Timestamp::new)
			.orElse(null);
	}

	@Override
	public DateTime convertToEntityAttribute(Timestamp dbData) {
		return Optional.ofNullable(dbData)
			.map(Timestamp::getTime)
			.map(DateTime::new)
			.orElse(null);
	}
}
